package com.example.demon1.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demon1.entity.User;
import com.example.demon1.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
//注意使用java11进行开发
@CrossOrigin
@RestController
public class UserController {
    @Autowired // 自动注入
    private UserMapper userMapper;

//    @GetMapping("/hello")
//    public String hello(){
//        return "hello world";
//    }

    @GetMapping("/query")
    public List<User> query(){

        return userMapper.selectList(null);
    }

//    @PostMapping("/add")
//    public int add(String username,String password){
//        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(User::getUsername,username).eq(User::getPassword,password);
//
//        User user=userMapper.selectOne(lambdaQueryWrapper);
//        return userMapper.insert(user);
//    }

        @PostMapping("/add")
    public int add(@RequestBody User user){
        return userMapper.insert(user);
    }
    @PostMapping("/update")
    public int update(@RequestBody User user){
        return userMapper.updateById(user);
        //更新时根据user.id去更新

    }

    @GetMapping("/delete")
    public int delete(Integer id){
        return userMapper.deleteById(id);

    }

    @GetMapping("/deleteList")
    public int delete(@RequestParam List<Integer> ids){
        return userMapper.deleteBatchIds(ids);

    }
    //分页查询
    @GetMapping("/queryByPage")
    public IPage<User> queryByPage(Integer pageSize , Integer pageNum,String username){
        IPage<User> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(User::getUsername,username);

        return userMapper.selectPage(page,lambdaQueryWrapper);
    }

    @GetMapping("/login")
    public String queryByPage(String username,String password){
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUsername,username).eq(User::getPassword,password);

        User user=userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(user)){
            return "账号未注册&用户名或密码错误";
        }
        else{
            return "登录成功";
        }
    }
}
